package com.pactera.jep.service.sys.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.core.holder.SpringContextHolder;
import com.pactera.jep.service.sys.security.spring.bean.UserEntity;

public class UserEntityUtil {

	private final static Logger logger = LoggerFactory.getLogger(UserEntityUtil.class);
	
	/**
	 * 获取当前登录用户
	 * 
	 * @return
	 */
	public final static UserEntity getCurrentUser() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		HttpSession session = request.getSession(false);
		// TODO:添加SSO登录的情况下从header中获取到UserEntity的步骤
		String authenticationProfile = SpringContextHolder.getApplicationContext().getEnvironment().getProperty("authentication.profile");
		if ("sso".equals(authenticationProfile)) {
			// 因为在zuul中做了处理，在cas登录的情况下数据会通过header带过来，所以可以从请求中获取数据
			return grabUserFromRequest();
		} else {
			if (session == null) {
				logger.debug("session is null.");
				return null;
			} else {
				SecurityContextImpl sci = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");
				if (sci == null) {
					logger.debug("sci is null");
					return null;
				} else {
					// 从SecurityContextImpl中获取数据
					Authentication authentication = sci.getAuthentication();
					if (authentication != null) {
						return (UserEntity) authentication.getPrincipal();
					}
					return null;
				}
			}
		}
	}
	
	/**
	 * 从请求中获取到用户数据(因为在cas登录情况下，用户数据将会保存在zuul的session中并将通过requestheader带过来)
	 * @return
	 */
	private final static UserEntity grabUserFromRequest() {
		// 首先获取到当前的请求
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		UserEntity userEntity = new UserEntity();
		String info = request.getHeader("auth_info");
		if (StringUtils.isBlank(info)) {
			logger.error("请求中不带有认证数据!");
		} else {
			// 因为后面从这获取的用户数据只需要用到用户编号，因此这里只需要读取到用户编号就可以了
			// 有其它需求后面再来添加
			JSONObject obj = JSON.parseObject(info);
			String id = obj.getString("userId");
			userEntity.setUserId(id);
		}
		return userEntity;
	}

}
